/*
 * @Descripttion:
 * @Author: cuidm
 * @Date: 2022-07-13 09:26:36
 * @LastEditors: cuidm
 * @LastEditTime: 2022-10-21 12:01:27
 */

import React, { useEffect, useState } from 'react';
import { Affix, Button, Alert, Radio, Select, Input, Space, Row, Col, Tree, message, Spin, Empty, Tooltip } from 'antd';
import { DownCircleOutlined, RightCircleOutlined, UploadOutlined, SearchOutlined } from '@ant-design/icons';
import { TempImportModal, Authorized } from '@/components';
import request, { exportFile } from '@/utils/request';
import cmdbres from '@/data/cmdbres';
import CreateGroup from '../createGroup';
import DeleteGroup from '../deleteGroup';
import CreateModel from '../createModel';
import EditModel from '../editModel';
import DeleteModel from '../deleteModel';
import ImportModal from './importModel';
import hcpUtils from '@/utils/hcpUtils';
import permission from '@/config/permission';
import './index.less';
const { DirectoryTree } = Tree;

const ModelTree = ({ history, match, location, biz, setSelectTreeNode }) => {
    const [loading, setLoading] = useState(true);
    const [expandedKeys, setExpandedKeys] = useState([]);
    const [selectedKeys, setSelectedKeys] = useState([]);
    const [allTreeData, setAllTreeData] = useState([]);
    const [treeData, setTreeData] = useState([]);
    const [autoExpandParent, setAutoExpandParent] = useState(true);

    const [showAddGroup, setShowAddGroup] = useState(false);
    const [showEditGroup, setShowEditGroup] = useState(false);
    const [showDeleteGroup, setShowDeleteGroup] = useState(false);
    const [showImportModal, setShowImportModal] = useState(false);
    const [showAddModule, setShowAddModule] = useState(false);
    const [showEditModule, setShowEditModule] = useState(false);
    const [showDeleteModule, setShowDeleteModule] = useState(false);
    const [showImportModule, setShowImportModule] = useState(false);
    const [info, setInfo] = useState({});
    const [searchValue, setSearchValue] = useState('');

    const renderTitle = (item) => {
        const { name, type } = item;
        const strTitle = item.name;
        const index = strTitle?.indexOf(searchValue);
        const beforeStr = strTitle?.substring(0, index);
        const afterStr = strTitle?.slice(index + searchValue.length);

        return (
            <>
                <span className="node-name" title={name}>
                    {index > -1 ? (
                        <span>
                            {beforeStr}
                            <span className="tree-search-value">{searchValue}</span>
                            {afterStr}
                        </span>
                    ) : (
                        <span>{strTitle}</span>
                    )}
                </span>
                {type == 'top' ? (
                    <Space>
                        <Authorized authority={permission.model_add} noMatch={null}>
                            <span
                                className="btn iconfont icon-plus"
                                onClick={async (e) => {
                                    e.stopPropagation();
                                    setShowAddGroup(true);
                                    setInfo(item);
                                }}
                            />
                        </Authorized>
                        <Authorized authority={permission.model_edit} noMatch={null}>
                            <span
                                className="btn iconfont icon-edit"
                                disabled={item.moduleClassificationType == 'inner'}
                                onClick={async (e) => {
                                    e.stopPropagation();
                                    if (item.moduleClassificationType == 'inner') {
                                        message.warning('内置模型组不支持修改');
                                        return;
                                    }
                                    setShowEditGroup(true);
                                    setInfo(item);
                                }}
                            />
                        </Authorized>
                        <Authorized authority={permission.model_delete} noMatch={null}>
                            <span
                                className="btn iconfont icon-delete"
                                disabled={item.moduleClassificationType == 'inner'}
                                onClick={async (e) => {
                                    e.stopPropagation();
                                    if (item.moduleClassificationType == 'inner') {
                                        message.warning('内置模型组不支持删除');
                                        return;
                                    }
                                    setShowDeleteGroup(true);
                                    setInfo(item);
                                }}
                            />
                        </Authorized>
                    </Space>
                ) : type == 'secondary' ? (
                    <Space>
                        <Authorized authority={permission.model_add} noMatch={null}>
                            <span
                                className="btn iconfont icon-plus"
                                onClick={async (e) => {
                                    e.stopPropagation();
                                    setShowAddModule(true);
                                    setInfo(item);
                                }}
                            />
                        </Authorized>
                        <Authorized authority={permission.model_edit} noMatch={null}>
                            <span
                                className="btn iconfont icon-edit"
                                disabled={item.moduleClassificationType == 'inner'}
                                onClick={async (e) => {
                                    e.stopPropagation();
                                    if (item.moduleClassificationType == 'inner') {
                                        message.warning('内置模型组不支持修改');
                                        return;
                                    }
                                    setShowEditGroup(true);
                                    setInfo(item);
                                }}
                            />
                        </Authorized>
                        <Authorized authority={permission.model_delete} noMatch={null}>
                            <span
                                className="btn iconfont icon-delete"
                                disabled={item.moduleClassificationType == 'inner'}
                                onClick={async (e) => {
                                    e.stopPropagation();
                                    if (item.moduleClassificationType == 'inner') {
                                        message.warning('内置模型组不支持删除');
                                        return;
                                    }
                                    setShowDeleteGroup(true);
                                    setInfo(item);
                                }}
                            />
                        </Authorized>
                        {/* <span
                            className="btn iconfont icon-daoru"
                            onClick={async(e)=>{
                                e.stopPropagation();
                                setShowImportModal(true);
                                setInfo(item);
                            }}
                        /> */}
                    </Space>
                ) : (
                    <Space>
                        <Authorized authority={permission.model_edit} noMatch={null}>
                            <span
                                className="btn iconfont icon-edit"
                                disabled={item.moduleDefinitionType == 'inner'}
                                onClick={async (e) => {
                                    e.stopPropagation();
                                    if (item.moduleDefinitionType == 'inner') {
                                        message.warning('内置模型不支持修改');
                                        return;
                                    }
                                    setShowEditModule(true);
                                    setInfo(item);
                                }}
                            />
                        </Authorized>
                        <Authorized authority={permission.model_delete} noMatch={null}>
                            <span
                                className="btn iconfont icon-delete"
                                disabled={item.moduleDefinitionType == 'inner'}
                                onClick={async (e) => {
                                    e.stopPropagation();
                                    if (item.moduleDefinitionType == 'inner') {
                                        message.warning('内置模型不支持删除');
                                        return;
                                    }
                                    setShowDeleteModule(true);
                                    setInfo(item);
                                }}
                            />
                        </Authorized>
                    </Space>
                )}
            </>
        );
    };

    const queryModel = async (isInit) => {
        try {
            setLoading(true);
            let res = await request({
                ...cmdbres.queryModelList,
                params: {
                    namespace: 'default',
                },
            });

            if (res && res.code == 200) {
                let defaultSelectedKey = null;
                let arr = []; //tree扁平化
                let moduleIcons = {};
                hcpUtils.treeDataIteration(res.data, function (item) {
                    if (item.definitions && item.definitions.length) {
                        item.children = item.children ? item.children.concat(item.definitions) : item.definitions;
                        if (!defaultSelectedKey) {
                            defaultSelectedKey = item.definitions[0].cmModuleId;
                            setSelectTreeNode(item.definitions[0]);
                        }
                        delete item.definitions;
                    }
                    if (item.cmModuleId) {
                        //是模型
                        item.key = item.cmModuleId;
                        item.name = item.moduleName;
                        item.icon = <span className={`iconfont ${item.moduleIcon}`}></span>;
                        item.type = 'module';
                        item.parentKey = item.moduleClassificationId;
                        moduleIcons[item.cmModuleId] = item.moduleIcon;
                    } else {
                        //是分组
                        item.key = item.id;
                        item.name = item.moduleClassificationName;
                        item.type = item.parentId ? 'secondary' : 'top'; //顶级和次级分组
                        if (!(item.definitions && item.children)) {
                            item.switcherIcon = null;
                        }
                        item.parentKey = item.parentId || 0;
                        item.icon = null;
                    }
                    arr.push({
                        key: item.key,
                        title: item.name,
                    });
                    item.displayName = item.name;
                    item.title = renderTitle(item);
                });
                if (isInit) {
                    setExpandedKeys([defaultSelectedKey]);
                    setSelectedKeys([defaultSelectedKey]);
                }
                setTreeData(res.data);
                setAllTreeData(arr);
                localStorage.setItem('moduleIcons', JSON.stringify(moduleIcons));
            }
            setLoading(false);
        } catch (error) {
            console.log(error);
        }
    };

    useEffect(() => {
        queryModel(true);
    }, []);

    const onExpand = (keys) => {
        setExpandedKeys(keys);
        setAutoExpandParent(false);
    };

    const onSelect = (selectedKeys, e) => {
        if (e.node.type == 'module') {
            setSelectedKeys(selectedKeys);
            if (setSelectTreeNode) {
                setSelectTreeNode(e.node);
            }
            return;
        }
        // 对expandedKeys进行拷贝
        let copyExpandedKeys = [...expandedKeys];
        // 节点处于未展开状态
        if (!e.node.expanded) {
            // 将节点key值存入到expandedKeys中
            copyExpandedKeys.push(e.node.key);
            setExpandedKeys(copyExpandedKeys);
        }
        // 节点处于已展开状态
        else {
            // 获取被点击节点key在expandedKeys中的下标值
            let expandedIndex = copyExpandedKeys.indexOf(e.node.key);
            // 将节点的key从expadedKeys中移除
            copyExpandedKeys.splice(expandedIndex, 1);
            setExpandedKeys(copyExpandedKeys);
        }
    };

    const getParentKey = (key, tree) => {
        let parentKey;

        for (let i = 0; i < tree.length; i++) {
            const node = tree[i];

            if (node.children) {
                if (node.children.some((item) => item.key === key)) {
                    parentKey = node.key;
                } else if (getParentKey(key, node.children)) {
                    parentKey = getParentKey(key, node.children);
                }
            }
        }

        return parentKey;
    };

    const onChange = (e) => {
        const { value } = e.target;
        const newExpandedKeys = allTreeData
            .map((item) => {
                if (item.title.indexOf(value) > -1) {
                    return getParentKey(item.key, treeData);
                }

                return null;
            })
            .filter((item, i, self) => item && self.indexOf(item) === i);
        setExpandedKeys(newExpandedKeys);
        setSearchValue(value);
        setAutoExpandParent(true);
    };

    const loop = (data) =>
        data.map((item) => {
            if (item.children) {
                return {
                    ...item,
                    title: renderTitle(item),
                    children: loop(item.children),
                };
            }

            return {
                ...item,
                title: renderTitle(item),
                key: item.key,
            };
        });

    useEffect(() => {
        const arr = loop(treeData);
        setTreeData(arr);
    }, [searchValue]);

    return (
        <div className="model-tree-box">
            <Input
                className="tree-search"
                placeholder="请输入模型名称"
                value={searchValue}
                onChange={onChange}
                style={{ marginBottom: 10 }}
                suffix={<SearchOutlined />}
            />
            <Row className="tree-opt-box">
                <Col span={19} style={{ paddingRight: 10 }}>
                    <Authorized authority={permission.model_add} noMatch={null}>
                        <div
                            className="tree-add-sort"
                            onClick={() => {
                                setShowAddGroup(true);
                                setInfo({});
                            }}
                        >
                            <span className="iconfont icon-plus"> 新增一级分类</span>
                        </div>
                    </Authorized>
                </Col>
                <Col span={5}>
                    <Authorized authority={permission.model_import} noMatch={null}>
                        <div
                            className="tree-add-sort"
                            onClick={() => {
                                setShowImportModule(true);
                            }}
                        >
                            <Tooltip title="导入模型" style={{ width: '100%' }}>
                                <div>
                                    <span className="iconfont icon-daoru"></span>
                                </div>
                            </Tooltip>
                        </div>
                    </Authorized>
                </Col>
            </Row>

            {loading ? (
                <Spin className="module-tree-spin" />
            ) : treeData.length ? (
                <Tree
                    className="module-tree"
                    showLine
                    showIcon
                    showLeafIcon={false}
                    // switcherIcon={<DownCircleOutlined />}
                    expandedKeys={expandedKeys}
                    selectedKeys={selectedKeys}
                    treeData={treeData}
                    onSelect={onSelect}
                    onExpand={onExpand}
                    autoExpandParent={autoExpandParent}
                    // defaultExpandParent
                />
            ) : (
                <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} />
            )}
            <CreateGroup
                title={info?.type == 'top' ? '新增子分类' : '新增一级分类'}
                parentId={info?.id}
                visible={showAddGroup}
                setVisible={setShowAddGroup}
                onCreateFinish={() => {
                    queryModel(true);
                }}
            />
            <CreateGroup
                info={info}
                title={info?.type == 'top' ? '编辑一级分类' : '编辑子分类'}
                groupId={info?.id}
                visible={showEditGroup}
                setVisible={setShowEditGroup}
                onCreateFinish={() => {
                    queryModel();
                }}
            />
            <DeleteGroup
                onDeleteFinish={() => {
                    queryModel();
                }}
                visible={showDeleteGroup}
                setVisible={setShowDeleteGroup}
                info={info}
            />
            <CreateModel
                onCreateFinish={() => {
                    queryModel();
                }}
                visible={showAddModule}
                setVisible={setShowAddModule}
                info={info}
            />
            <EditModel
                onEditFinish={() => {
                    queryModel();
                }}
                visible={showEditModule}
                setVisible={setShowEditModule}
                info={info}
            />
            <TempImportModal
                title="导入模型"
                visible={showImportModal}
                setVisible={setShowImportModal}
                onImportFinish={() => {
                    queryModel();
                }}
                downloadApi="模型导入模板.xlsx" // 下载模板
                downloadURL={'/module/export/export-definition-excel'} // 下载地址
                importApi={cmdbres.importModel} // 导入地址
                description={'支持格式：xlsx、xls，且不超过200M'}
                size={200 * 1024 * 1024}
            />
            <DeleteModel
                onDeleteFinish={() => {
                    queryModel();
                }}
                visible={showDeleteModule}
                setVisible={setShowDeleteModule}
                info={info}
            />
            <ImportModal
                visible={showImportModule}
                setVisible={setShowImportModule}
                onImportFinish={() => {
                    queryModel(true);
                }}
            />
        </div>
    );
};

export default ModelTree;
